<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>列表渲染指令</title>
</head>
<body>
    <div id="app">
        <ul>
            <li v-for="book in books">{{book.name}}</li>
            <li v-for="(book,index) in books">{{index}} - {{book.name}}</li>
            <template v-for="book in books">
                <li>书名：{{book.name}}</li>
                <li>作者：{{book.author}}</li>
            </template>
        </ul>
        <span><button @click="add">添加</button></span>
        <span><button @click="filte">过滤</button></span>
        <span><button @click="modify">修改</button></span>
        <span><button @click="modifyLength">修改长度</button></span>
        <ul>
            <li v-for="book in sortedBooks">{{book.name}}</li>
        </ul>
    </div>
    <script src="https://unpkg.com/vue/dist/vue.js"></script>
    <script>
        var app = new Vue({
            el: '#app',
            data: {
                books:[
                    {name: '《Vue.js》',author:'梁灏'},
                    {name: '《JavaScript语言精粹》',author: 'Douglas Crockford'},
                    {name: '《JavaScript高级程序设计》',author: 'Nicholas C.Zakas'},
                ]
            },
            computed:{
                sortedBooks: function(){
                    return this.books.sort(function (a,b){
                        return a.name.length < b.name.length;
                    })
                }
            },
            methods:{
                add:function (){
                    app.books.push({
                        name:'《CSS揭秘》',
                        author:'[希] Lea Verou'
                    })
                },
                filte:function (){
                   app.books =  app.books.filter(function (item){
                        return item.name.match(/JavaScript/)
                    })
                },
                modify:function () {
                    /*通过索引直接设置项，比如app.books[3]={...}，不会触发视图更新*/
                    this.$set(app.books,3,{
                        name:'《CSS解密》',
                        author:'[希] Lea Verou'
                    })
                },
                modifyLength:function (){
                    /*修改数组长度，比如app.books.length=1,不会触发视图更新*/
                    app.books.splice(1)
                }
            }
        })
    </script>
</body>
</html>
